package com.sdy.kzyy.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sdy.common.model.BizException;
import com.sdy.common.utils.Assert;
import com.sdy.common.utils.DateUtil;
import com.sdy.common.utils.StringUtil;
import com.sdy.kzyy.biz.constants.Constants;
import com.sdy.kzyy.biz.dto.OrderRecordInfoDTO;
import com.sdy.kzyy.biz.dto.OrderRecordDTO;
import com.sdy.kzyy.biz.dto.RecordInfoDTO;
import com.sdy.kzyy.biz.model.OrderRecord;
import com.sdy.kzyy.biz.mapper.OrderRecordMapper;
import com.sdy.kzyy.biz.service.OrderRecordService;
import com.sdy.kzyy.biz.service.UserService;
import com.sdy.mvc.service.impl.BaseServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zzq
 * @since 2020-03-03
 */
@Slf4j
@Service
public class OrderRecordServiceImpl extends BaseServiceImpl<OrderRecord> implements OrderRecordService {
    @Resource
    private OrderRecordMapper orderRecordMapper;
    @Autowired
    private OrderRecordService orderRecordService;
    @Autowired
    private UserService userService;

    @Override
    public OrderRecordInfoDTO getOrderRecordInfo(String token) throws BizException{
        Assert.isNull(token, "无法获取二维码信息");
        OrderRecordInfoDTO orderRecordInfo = orderRecordMapper.getOrderRecordInfo(token);
        Assert.isNull(orderRecordInfo, "无法获取二维码信息");
        Assert.isTrue(StringUtil.isBlank(orderRecordInfo.getAreaName()), "无法获取预约网店的区域信息");
        Assert.isTrue(StringUtil.isBlank(orderRecordInfo.getAddress()), "无法获取预约网店的具体地址信息");
        orderRecordInfo.setTotalAddress(Constants.REGION_CITY_NAME + orderRecordInfo.getAreaName() + orderRecordInfo.getAddress());
//        orderRecordInfo.setAppointTime(getStringByDate(orderRecordInfo.getOrderTime(), orderRecordInfo.getAppointTime()));
        orderRecordInfo.setAppointTime((orderRecordInfo.getWeek() + " \n " + orderRecordInfo.getWeekTime()));
        return orderRecordInfo;
    }

    @Override
    public Boolean confirmMasksGot(String orderId, Integer userId) throws BizException {
        OrderRecord orderRecord = orderRecordService.getOne(new LambdaQueryWrapper<OrderRecord>().eq(OrderRecord::getOrderId, orderId));
        Assert.isNull(orderRecord, "无法获取该订单信息");
        Assert.isTrue((DateUtil.formatDate(new Date()).equals(DateUtil.formatDate(orderRecord.getOrderTime()))), "当天的订单请隔天来取口罩");
        Assert.isTrue(orderRecord.getReceiveStatus().equals("2"), "订单已完成，无法重复领取口罩");
        Assert.isTrue(orderRecord.getOrderStatus().equals("1"), "订单已失效");
        Assert.notTrue((orderRecord.getOrderStoreCode().equals(userService.getById(userId).getStoreCode())), "该预约人订单的自提网点不是当前网点");
        boolean update = orderRecordService.update(new LambdaUpdateWrapper<OrderRecord>()
                .eq(OrderRecord::getOrderId, orderId)
                .set(OrderRecord::getReceiveStatus, 2)
                .set(OrderRecord::getReceiveTime, new Date())
                .set(OrderRecord::getReceiveUserId, userId));
        return update;
    }

    @Override
    public List<OrderRecordDTO> getSelfOrderAll(Integer userId) throws BizException {
        /*List<String> idCards = personalInformationService.list(Wrappers.<PersonalInformation>lambdaQuery()
                .eq(PersonalInformation::getUserId, userId))
                .stream().map(PersonalInformation::getCard).collect(Collectors.toList());*/
        List<OrderRecord> list = orderRecordService.list(Wrappers.<OrderRecord>lambdaQuery().eq(OrderRecord::getUserId, userId));

        Assert.isTrue(list.isEmpty(), "尚未有您的订单信息!");
        List<OrderRecordDTO> selfOrderAll = orderRecordMapper.getSelfOrderAll(userId);
        for (OrderRecordDTO onOrder : selfOrderAll) {
            onOrder.setAreaName(onOrder.getAreaName() == null ? "" : onOrder.getAreaName());
            onOrder.setStoreName(onOrder.getStoreName() == null ? "" : onOrder.getStoreName());
            onOrder.setAddress(onOrder.getAddress() == null ? "" : onOrder.getAddress());
            onOrder.setSelfInitiatedNetwork(onOrder.getAreaName() + onOrder.getStoreName())
                    .setDotAddress(Constants.REGION_CITY_NAME + onOrder.getAreaName() + onOrder.getAddress());
//            onOrder.setAppointTime(getStringByDate(onOrder.getOrderTime(), onOrder.getAppointTime()));
            onOrder.setAppointTime((onOrder.getWeek() + " \n " + onOrder.getWeekTime()));
        }
        return selfOrderAll;
    }

    @Override
    public RecordInfoDTO getRecordInfoById(Integer id) throws BizException {
        Assert.isNull(id, "缺少必要参数");
        RecordInfoDTO recordInfoById = orderRecordMapper.getRecordInfoById(id);
        if (null == recordInfoById) {
            return null;
        }
        recordInfoById.setSite(recordInfoById.getAName() + recordInfoById.getSName());
        recordInfoById.setSiteAddress(Constants.REGION_CITY_NAME + recordInfoById.getAName() + recordInfoById.getAddress());
//        recordInfoById.setAppointTime(getStringByDate(recordInfoById.getOrderTime(), recordInfoById.getAppointTime()));
        recordInfoById.setAppointTime((recordInfoById.getWeek() + " \n " + recordInfoById.getWeekTime()));
        return recordInfoById;
    }

    @Override
    public Integer getOrderNumber(String storeCode, String orderTime) {
        return orderRecordMapper.getOrderNumber(storeCode, orderTime);
    }

    @Override
    public boolean insertNewOrder(OrderRecord orderRecord) {
        if (save(orderRecord)) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public List<OrderRecord> getRecordInfoByCardId(String card) throws BizException {
        Assert.isNull(card, "缺少身份信息");
        QueryWrapper<OrderRecord> wrapper = new QueryWrapper<>();
        wrapper.eq("order_card", card);
        wrapper.orderByDesc("order_time");
        return list(wrapper);
    }

    @Override
    public List<OrderRecord> getOnedayRecordInfoByCardId(String card) {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");//设置日期格式
        String nowTime = df.format(new Date());
        QueryWrapper<OrderRecord> wrapper = new QueryWrapper<>();
        wrapper.eq("order_card", card);
        wrapper.likeRight("order_id", nowTime);
        return list(wrapper);
    }

/*    *//**
     * 可领取口罩日期间隔
     * @param date 订单时间
     * @return
     *//*
    private String getStringByDate(Date date, String appointment) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        long time = 0L;
        try {
            time = df.parse(df.format(date)).getTime();
        } catch (Exception e) {
            return null;
        }
        long first = time + 24 * 60 * 60 * 1000L;
        long next = time + Long.parseLong(keyValueConfigurationsService.getOverdueDate()) * 24 * 60 * 60 * 1000L;
        return (df.format(new Date(first)) + " 至 " + df.format(new Date(next)) + " \n " + appointment);
    }*/

}
